package com.example.mvplibrary.presenter;

import com.example.mvplibrary.model.BaseModel;
import com.example.mvplibrary.view.BaseView;
import com.trello.rxlifecycle2.LifecycleProvider;

import java.lang.ref.WeakReference;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class BasePresenter<V extends BaseView, M extends BaseModel> implements RxPresenter<V> {
    //弱引用
    private WeakReference<V> weakReference;

    private V view;
    private M model;

    @Override
    public void bindView(V v) {
        weakReference = new WeakReference<V>(v);
        view = weakReference.get();
//                    if(weakReference!=null){
//            Log.e("liangxq", "bindView: "+v.getClass() );
//            view= (V) Proxy.newProxyInstance(weakReference.get().getClass().getClassLoader(), weakReference.get().getClass().getInterfaces(), new InvocationHandler() {
//                @Override
//                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                    if(weakReference==null||weakReference.get()==null){
//                        return null;
//                    }
//                    return method.invoke(weakReference.get(),args);
//                }
//            });
//        }
        initModel();

//        initModels();

    }

    @Override
    public void destroyView() {
        if (weakReference != null) {
            weakReference.clear();
            weakReference = null;
        }
        if (view != null) {
            view = null;
        }
    }

//    private void initModels() {
//        ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass();
//        Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();
//        Class<M> modelClass= (Class<M>) actualTypeArguments[1];
//        try {
//            model = modelClass.newInstance();
//
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (InstantiationException e) {
//            e.printStackTrace();
//        }
//    }

    //利用反射动态创建model
    private void initModel() {
        ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass();
        Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();
        Class<M> modelClass = (Class<M>) actualTypeArguments[1];
        try {
            model = modelClass.newInstance();

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }


    public V getView() {
        return view;
    }

    @Override
    public LifecycleProvider getLifecycleProvider() {
        if (getView() != null) {
            return (LifecycleProvider) getView();
        }
        return null;
    }

    public M getModel() {
        return model;
    }
}
